/*****************************************************************
 * data2json(csv_data)				csv字符串转json字符串
 * date2stamp(date)					日期转时间戳 （2018/05/08）
 * getDateDiff(dateStr)				时间戳转日期
 * formatDate(time)					时间戳转日期2（用于提示更新时间 2022-04-03 18:09:02）
 * sort_by_time(json)				json按照时间排序
 * ShowMainData(json)               主页显示主要数据（alldata，inout）所有消费，收入支出
 * ShowBalanceData(json)			显示余额数据
 * ShowCategory(list)				设置分类数据
 *****************************************************************/

/*****************************************************************
 *
 * csv字符串转json字符串
 *
 *****************************************************************/
data2json = function(csv_data) {
	data = [];
	data_list = csv_data.split("\n");
	data_title_list = data_list[0].split(",");
	for(i=1;i<data_list.length;i++) {
		tmp = {};
		array = data_list[i].split(",");
		for(j=0; j<array.length; j++) {
			tmp[data_title_list[j]] = array[j];
		}
		data[i-1] = tmp;  
	}
	return data;
}
/*****************************************************************
 *
 * 日期转时间戳 （2018/05/08）,输出number类型的时间戳（毫秒）
 *
 *****************************************************************/
date2stamp = function(date) {
	let d = new Date(date);
	return d.getTime(d);
}

/*****************************************************************
 *
 * 时间戳转日期
 * getDateDiff(new Date(Number(时间戳字符串)).Format("yyyy-MM-dd hh:mm:ss"))
 *
 *****************************************************************/
getDateDiff = function(dateStr) {
        var publishTime = getDateTimeStamp(dateStr) / 1000,
        d_seconds,
        d_minutes,
        d_hours,
        d_days,
        timeNow = parseInt(new Date().getTime() / 1000),
        d,
 
        date = new Date(publishTime * 1000),
        Y = date.getFullYear(),
        M = date.getMonth() + 1,
        D = date.getDate(),
        H = date.getHours(),
        m = date.getMinutes(),
        s = date.getSeconds();
        //小于10的在前面补0
        if (M < 10) {
                M = '0' + M;
        }
        if (D < 10) {
                D = '0' + D;
        }
        if (H < 10) {
                H = '0' + H;
        }
        if (m < 10) {
                m = '0' + m;
        }
        if (s < 10) {
                s = '0' + s;
        }
 
        d = timeNow - publishTime;
        d_days = parseInt(d / 86400);
        d_hours = parseInt(d / 3600);
        d_minutes = parseInt(d / 60);
        d_seconds = parseInt(d);
 
        if (d_days > 0 && d_days < 3) {
                return d_days + '天前';
        } else if (d_days <= 0 && d_hours > 0) {
                return d_hours + '小时前';
        } else if (d_hours <= 0 && d_minutes > 0) {
                return d_minutes + '分钟前';
        } else if (d_seconds < 60) {
                if (d_seconds <= 0) {
                        return '刚刚';
                } else {
                        return d_seconds + '秒前';
                }
        } else if (d_days >= 3 && d_days < 30) {
                return M + '-' + D;
        } else if (d_days >= 30) {
                return Y + '-' + M + '-' + D;
        }
}
 
getDateTimeStamp = function(dateStr) {
	// 如果时间格式为2020/07/09 21:43:19.000  需要去掉.000 不然ios和firefox会有问题          
	return Date.parse(dateStr.replace(/-/gi, "/"));
}　　

//console.log(this.getDateDiff("2020-07-03 10:03:19.000"));

Date.prototype.Format = function (fmt) { //author: meizz
	var o = {
		"M+": this.getMonth() + 1, //月份
		"d+": this.getDate(), //日
		"h+": this.getHours(), //小时
		"m+": this.getMinutes(), //分
		"s+": this.getSeconds(), //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds() //毫秒
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
	if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}


formatDate = function(now_int) {
	let date = new Date(now_int);
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    let D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
    let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    let m = (date.getMinutes() <10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    let s = (date.getSeconds() <10 ? '0' + date.getSeconds() : date.getSeconds());
    let completeTime = Y+M+D+h+m+s;
    let inCompleteTime = Y+M+D;
    return completeTime;
}
/*****************************************************************
 *
 * json按照时间排序
 * json = sort_by_time(json);
 *
 *****************************************************************/
sort_by_time = function(json) {
	sort_rule = function(a, b) {
		return Number(date2stamp(b["支付日期"])) - Number(date2stamp(a["支付日期"]));
	}
	return json.sort(sort_rule);
}


/*****************************************************************
 *
 * 主页显示主要数据（alldata，inout）所有消费，收入支出
 * ShowMainData(json)
 *
 *****************************************************************/
ShowMainData = function(json) {
    // [ 0       1       2       3      4]
    // ["5797.65","中国银行","2021/11/29","贷款","贷款扣除学费后反回"]
	// 金额,支付途径,支付日期,标签,详情
	
	// 显示统计数据
	in_sum = 0;
	out_sum = 0;
	for(i=0;i<json.length;i++) {
		if(!json[i]["金额"]) continue;
		money = Number(json[i]["金额"]);
		if(money>0) in_sum += money;
		else out_sum -= money;
	}
	all_sum = in_sum - out_sum;
	if(all_sum>0) {money_str = "总计收入："; money_url = "不错嘛，现在是收入大于支出哦！"}
	else if(all_sum<0) {all_sum = -all_sum; money_str = "总计支出："; money_url = "在这方面是支出大于收入，要注意一下哦！"}
	else {money_str = "收支平衡"; money_url = "这也太巧了吧，收入与支出相等!"}
	d.push({
		title: '““””<font color="#FF1493"><b>' + "收入：" + String(in_sum.toFixed(2)) + '元</b></font>',
		url: 'toast://收入不少嘛！',
		col_type: "text_2"
	});
	d.push({
		title: '““””<font color="#FF1493"><b>' + "支出：" + String(out_sum.toFixed(2)) + '元</b></font>',
		url: 'toast://注意消费哦！',
		col_type: "text_2"
	});
	d.push({
		title: '““””<font color="#FF1493"><b>' + money_str + String(all_sum.toFixed(2)) + '元</b></font>',
		url: 'toast://' + money_url,
		col_type: "text_center_1"
	});
	// 显示所有数据
	for(i=0;i<json.length;i++) {
	    if(!json[i]["金额"]) continue;
		json_str = JSON.stringify(json[i]);
		time = getDateDiff(new Date(Number(date2stamp(json[i]["支付日期"]))).Format("yyyy-MM-dd"));
		desc = '““””💰 <font color="#9932CC"><big><b>' + json[i]["金额"] +  '““””</b></big></font>' + '““””&emsp;&emsp;🚀 <font color="#DC143C"><b>' + json[i]["支付途径"] +  '““””</b></font>' + '““””&emsp;&emsp;⌚ <font color="red">' + time + '““””</font>' + '““””<br><br>' + json[i]["详情"];
		putMyVar("DESC"+ String(i), desc);
		d.push({
			title: '““””<font color="#FF1493"><b>' + json[i]["标签"] + '</b></font>',
			desc: desc,
			url: $("hiker://empty##" + json_str + "empty##" + String(i)).rule(()=>{
				d = [];
				json = JSON.parse(MY_URL.split("empty##")[1]); 
				desc = getMyVar("DESC" + MY_URL.split("empty##")[2]);
				d.push({
					title: '““””<h1><font color="#FF1493">' + json["标签"] + '““””</font></h1>',
					desc: desc.split("““””<br><br>")[0],
					url: 'toast://点我干嘛？！',
					col_type: "text_1"
				});
				d.push({
					title: json["详情"],
					col_type: "rich_text"
				});
				d.push({
					col_type: "line",
				});
				d.push({
					title: '““””💰 <font color="#D02090"><big><b>' + json["金额"] +  '““””</b></big></font>',
					col_type: "text_center_1",
					url: 'toast://这是金额😄',
					extra: {textSize: 48}
				});
				setResult(d);
			}),
		});
	}
	return d;
}

/*****************************************************************
 *
 * 主页显示余额数据（balance）
 * ShowBalanceData(json)
 *
 *****************************************************************/
ShowBalanceData = function(json) {
	for(i=0;i<json.length;i++) {
		if(!json[i][""]) continue;
		d.push({
			title: '““””<font color="#FF1493"><b>' + json[i][""] + '</b></font>',
			url: 'toast://点我没有用哦！',
			col_type: "text_2",
		});
		d.push({
			title: '““””<font color="#9932CC"><big><b>' + json[i]["余额"]  + '</big>元</b></font>',
			url: 'toast://点我没有用哦！',
			col_type: "text_2",
		});
	}
	return d;
}

/*****************************************************************
 *
 * 设置分类数据
 * ShowCategory(list)				
 *
 *****************************************************************/
ShowCategory = function(list_dis, flag_var) {
	Color = "#39B27A";
	flag = getMyVar(flag_var, "0");
	for(var a = 0; a < list_dis.length; a++) {
		var title = (a == Number(flag)) ? "““””<b>" + '<font color=' + Color + '>' + list_dis[a] + '</font></b>' : list_dis[a];
		d.push({
			title: title,
			url: $("#noLoading#").lazyRule((flag_var, flag) => {
				putMyVar(flag_var, flag);
				refreshPage(false);
				return "hiker://empty"
			}, flag_var, String(a)),
			col_type: 'scroll_button'
		});
	}
	d.push({
		col_type: "blank_block"
	});
}

/*****************************************************************
 *
 * 显示折叠展开按钮
 * ShowUnfoldCollapse(list)				
 *
 *****************************************************************/
ShowUnfoldCollapse = function() {
	Unfold_and_Collapse_List = ['““””<b><span style="color: #1aad19">∨</span></b>', '““””<b><span style="color: #FF0000">∧</span></b>'];
	ind = Number(getMyVar("Unfold_and_Collapse_Ind", "0")); // 0代表折叠
	title = Unfold_and_Collapse_List[ind];
	d.push({
		title: title,
		url: $("#noLoading#").lazyRule((ind) => {
			putMyVar("Unfold_and_Collapse_Ind", String(1-ind)); // 状态翻转
			refreshPage(false);
			return "hiker://empty"
		}, ind),
		col_type: 'scroll_button'
	});
}

/*****************************************************************
 *
 * 获取分类数据
 * GetCategoryList(json)				
 *
 *****************************************************************/
GetCategoryList = function(json) {
	// [ 0       1       2       3      4]
    // ["5797.65","中国银行","2021/11/29","贷款","贷款扣除学费后反回"]
	// 金额,支付途径,支付日期,标签,详情
	obj = {};
	dic_label = {};
	dic_year = {};
	dic_month = {};
	for(i=0;i<json.length;i++) {
		if(!json[i]["标签"]) continue;
		if(!json[i]["支付日期"]) continue;
		dic_label[json[i]["标签"]] = "";
		year = json[i]["支付日期"].split('/')[0];
		dic_year[year] = "";
		month = json[i]["支付日期"].split('/')[1];
		dic_month[month] = "";
	}
	
	arr = [];
	for(var key in dic_label) {
		arr.push(key);
	}
	arr.sort();
	arr.unshift("标签");
	obj["标签"] = arr;
	
	arr = [];
	for(var key in dic_year) {
		arr.push(key);
	}
	arr.sort();
	arr.unshift("年份");
	obj["年份"] = arr;
	
	arr = [];
	for(var key in dic_month) {
		arr.push(key);
	}
	arr.sort();
	arr.unshift("月份");
	obj["月份"] = arr;
	
	return obj;
}

/*****************************************************************
 *
 * 获取分类后json
 * GetCategoryData(json)				
 *
 *****************************************************************/
GetCategoryData = function(json) {
	new_json = [];
	for(i=0;i<json.length;i++) {
		if(!json[i]["标签"]) continue;
		if(!json[i]["支付日期"]) continue;
		target = obj["标签"][Number(getMyVar("label_set"))];
		if(target!="标签" && target!=json[i]["标签"]) continue;
		year = json[i]["支付日期"].split('/')[0];
		target = obj["年份"][Number(getMyVar("year_set"))];
		if(target!="年份" && target!=year) continue;
		month = json[i]["支付日期"].split('/')[1];
		target = obj["月份"][Number(getMyVar("month_set"))];
		if(target!="月份" && target!=month) continue;
		new_json.push(json[i]);
	}
	return new_json;
}